package org.edu.modules.enroll.controller;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.PutObjectResult;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.edu.common.api.vo.Result;
import org.edu.common.aspect.annotation.AutoLog;
import org.edu.common.system.vo.LoginUser;
import org.edu.modules.enroll.entity.*;
import org.edu.modules.enroll.service.*;
import org.edu.modules.enroll.util.OssDownloadUtil;
import org.edu.modules.enroll.vo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.*;
import java.io.File;
import java.io.IOException;
import java.util.zip.ZipEntry;

/**
 * @Author: 陈炜凡
 * @Description: TODO
 * @DateTime: 2021/7/27 16:49
 */
@Api(tags="招生公共")
@RestController
@RequestMapping("enroll/public")
@Slf4j
public class VeEnrollPublicController {
    @Resource
    private VeZsRegistrationService veZsRegistrationService;
    @Resource
    private VeDictQuarterService veDictQuarterService;
    @Resource
    private IVeBaseManageService iVeBaseManageService;
    @Resource
    private VeZsEnrollService veZsEnrollService;
    @Resource
    private VeZsAdmissionInformationService veZsAdmissionInformationService;
    @Resource
    private VeDictAreaService veDictAreaService;
    @Resource
    private VeDictXueziService veDictXueziService;
    @Resource
    private SysDictItemService sysDictItemService;
    @Resource
    private VeZsFenbanService veZsFenbanService;
    @Resource
    private VeDormSusheService veDormSusheService;
    @Resource
    private VeDormStudentService veDormStudentService;
    @Resource
    private VeFenSusheService veFenSusheService;
    @Autowired
    private VeZsPayInfoService veZsPayInfoService;
    @Resource
    private OSS ossClient;

    @Resource
    private SysDictService sysDictService;

    @Resource
    private VeZsStudentLoanService veZsStudentLoanService;

    @Resource
    private VeZsPlanService veZsPlanService;

    @Resource
    private VeZsReportMessageService veZsReportMessageService;

    @Resource
    private VeBaseGradeService veBaseGradeService;
    @Resource
    private VeBaseFacultyService veBaseFacultyService;

    @Resource
    private VeBaseSpecialtyService veBaseSpecialtyService;
    @ApiOperation(value="网上报名添加")
    @PostMapping(value = "/onlineCreate")
    public Result<?> addMng(ReplaceVo replaceVo){
        //数据校验
        //身份证号唯一
        QueryWrapper<VeZsRegistration> wrapper = new QueryWrapper<>();
        wrapper.eq("SFZH",replaceVo.getSfzh());
        VeZsRegistration veZsRegistration= veZsRegistrationService.getOne(wrapper);
        if(veZsRegistration!=null){
            return Result.error("添加失败，身份证号已存在");
        }else{
            //创建数据库对象
            VeZsRegistration ve=new VeZsRegistration();
            //获取当前招生季
            QueryWrapper<VeDictQuarter> wrapperA = new QueryWrapper<>();
            wrapperA.eq("isCur",1);
            //
            VeDictQuarter veDictQuarter= veDictQuarterService.getOne(wrapperA);
            if(null==veDictQuarter){
                return Result.error("添加失败，当前招生季信息有误");
            }
            String rxny=veDictQuarter.getRxny();
            String rxnf=veDictQuarter.getYear();
            //通过年份查找年级ID
            QueryWrapper<VeBaseGrade> wrapperGrade = new QueryWrapper<>();

            wrapperGrade.eq("NJMC",rxnf+"级");
            VeBaseGrade veBaseGrade = veBaseGradeService.getOne(wrapperGrade);//2021.9.2
//            --------------------------林彬辉
//            BasicResponseBO<List<VeBaseGrade>> listBasicResponseBO = iVeBaseManageService.getGradeAll();
//            List<VeBaseGrade> list = listBasicResponseBO.getResult();
//            VeBaseGrade veBaseGrade = null;
//            for (VeBaseGrade v :list){
//                if (v.getNjmc().equals(rxnf+"级")){
//                    veBaseGrade = v;
//                }
//            }
//            -------------------------------
            if(veBaseGrade==null){
                return Result.error("添加失败，招生季年份信息有误");
            }

            long zsj=veDictQuarter.getId();
            ve.setBmh(replaceVo.getSfzh());
            ve.setXm(replaceVo.getXm());
            ve.setCym(replaceVo.getCym());
            ve.setSfzh(replaceVo.getSfzh());
            ve.setZslx(replaceVo.getZslx());
            ve.setKsh(replaceVo.getKsh());
            ve.setZkzh(replaceVo.getZkzh());
            ve.setXbm(replaceVo.getXbm());
            ve.setCsrq(replaceVo.getCsrq());
            ve.setJg(replaceVo.getJg());
            ve.setMzm(replaceVo.getMzm());
            ve.setGatqwm("");
            ve.setJkzkm(replaceVo.getJkzkm());
            ve.setZzmmm(replaceVo.getZzmmm());
            ve.setZsqdm("");
            ve.setXslxdh(replaceVo.getXslxdh());
            ve.setSfsldrk("");
            ve.setDzxx(replaceVo.getDzxx());
            ve.setJstxh(replaceVo.getJstxh());
            ve.setProvince(replaceVo.getProvince());
            ve.setIsAdmit(0);
            ve.setIsReport(0);
            ve.setEnrollNum(0L);
            ve.setCcm("");
            ve.setCity(replaceVo.getCity());
            ve.setZymc(replaceVo.getZymc());
            ve.setCounty(replaceVo.getCounty());
            ve.setJtdz(replaceVo.getJtdz());
            ve.setJtyb(replaceVo.getJtyb());
            ve.setJtlxdh(replaceVo.getJtlxdh());
            ve.setTc(replaceVo.getTc());
            ve.setBmfsm("");
            ve.setYhkh("");
            ve.setByxx(replaceVo.getByxx());
            ve.setCreateTime(new Date());
            ve.setUpdateTime(new Date());
            ve.setTerminalId(1L);
            ve.setSfdb(replaceVo.getSfdb());
            ve.setRxny(rxny);
            ve.setGradeId(veBaseGrade.getId());
            //无须插入
            ve.setClassId(null);
            ve.setRxnf(rxnf);
            ve.setJdfs(replaceVo.getJdfs());
            //无须插入
            ve.setApplyTime(null);
            ve.setZsj(zsj);
            ve.setHklbm(replaceVo.getHklbm());
            ve.setQrcodeUrl(null);
            ve.setYxmc(replaceVo.getYxmc());
            ve.setIsDeleted(0);
            //同代报名的区别
            ve.setIsCheck(0);
            //数据类型转换
            Double kszf=0.0;
            if(replaceVo.getKszf()!="" && replaceVo.getKszf()!=null){
                kszf=Double.parseDouble(replaceVo.getKszf());
            }
            Long falid=Long.parseLong(replaceVo.getFalId());
            Long specId=Long.parseLong(replaceVo.getSpecId());
            Long xz=Long.parseLong(replaceVo.getXz());
            Long provinceId=Long.parseLong(replaceVo.getProvinceId());
            Long countyId=Long.parseLong(replaceVo.getCountyId());
            Long cityId=Long.parseLong(replaceVo.getCityId());
            ve.setKszf(kszf);
            ve.setFalId(falid);
            ve.setSpecId(specId);
            ve.setXz(xz);
            ve.setProvinceId(provinceId);
            ve.setCityId(cityId);
            ve.setCountyId(countyId);

            //添加数据
            boolean result= veZsRegistrationService.save(ve);
            if(result){
                return Result.OK("添加成功");
            }
            return Result.error("添加数据失败");
        }
    }

    @AutoLog(value = "录取管理-正式录取")
    @ApiOperation(value = "正式录取")
    @PostMapping("/getFormalAdmissionList")
    public Result<?> getFormalAdmissionList(@ApiParam("考生号") @RequestParam("KSH") String KSH,
                                            @ApiParam("姓名") @RequestParam("XM") String XM,
                                            @ApiParam("身份证号") @RequestParam("SFZH") String SFZH) {
        HashMap<String, Object> map = new HashMap<>();
        FormalInfoVo formalAdmissionVo = veZsEnrollService.getFormalAdmission(XM, KSH, SFZH);
        map.put("result",formalAdmissionVo);
        return Result.OK(map);
    }

    @ApiOperation(value="获取报名信息集合")
    @PostMapping(value = "/applyMsg")
    public Result<?> getApplyMsgList(@ApiParam("姓名") @RequestParam("XM") String XM,
                                     @ApiParam("考生号") @RequestParam("KSH") String KSH,
                                     @ApiParam("身份证号") @RequestParam("SFZH") String SFZH) {
        HashMap<String,Object> map = new HashMap<>();
        VeZsAdmissionInformation veZsAdmissionInformation=veZsAdmissionInformationService.applyMsg(XM, KSH, SFZH);
        map.put("result", veZsAdmissionInformation);
        return Result.ok(map);
    }

    @ApiOperation(value="准考证查询")
    @PostMapping(value = "/getVeZsAdmission")
    public Result<?> getVeZsAdmissionFormation(@ApiParam("姓名") @RequestParam("XM") String XM,
                                               @ApiParam("准考证号") @RequestParam("KSH") String KSH,
                                               @ApiParam("身份证号") @RequestParam("SFZH") String SFZH){
        HashMap<String,Object> map = new HashMap<>();
        AdmissionTicketInfoVo admissionTicketInfoVo =veZsAdmissionInformationService.selectByXmKshSfzh(XM, KSH, SFZH);
        map.put("result",admissionTicketInfoVo);
        return Result.ok(map);
    }

    //李少君
    @ApiOperation(value="网上报名")
    @PostMapping(value = "/baoming")
    public Result<?> baoming(@RequestBody VeZsSingleEnrollExpansion veZsSingleEnrollExpansion){
        veZsEnrollService.insertBaomingMessage(veZsSingleEnrollExpansion);
        return Result.OK("报名成功");
    }

    @ApiOperation(value="获取学制列表")
    @PostMapping(value = "/getXuezi")
    public Result<?> getXuezi(){

        List<VeDictXuezi> list = veDictXueziService.list();
        return Result.OK(list);
    }


    @ApiOperation(value="获取数据字典信息")
    @PostMapping(value = "/getSysDict")
    public Result<?> getSysDict(@ApiParam("字典字段") @RequestParam("dictCode") String dictCode){

        QueryWrapper<SysDict> wrapper1 = new QueryWrapper<>();
        wrapper1.eq("dict_code",dictCode);
        SysDict sysDict = sysDictService.getOne(wrapper1);

        QueryWrapper<SysDictItem> wrapper = new QueryWrapper<>();
        wrapper.eq("dict_id",sysDict.getId());
        List<SysDictItem> list = sysDictItemService.list(wrapper);
        return Result.OK(list);

    }

    //(自动分班)查询计划人数分班表格
    @AutoLog(value = "显示表格")
    @ApiOperation(value="显示表格", notes="显示表格")
    @PostMapping("/ShowList")
    public Result<?> giveBanji(@RequestParam(value = "gradeId") Integer gradeId,
                               @RequestParam(value = "specId") Integer specId,
                               @RequestParam(value = "enrollType") String enrollType,
                               @RequestParam(value = "falId") Integer falId
    ){
        List<VeZsFenbanVo> list = veZsFenbanService.getZidongFenbanList(gradeId, specId, falId, enrollType);
        if(list==null){
            return Result.error("该条件下无班级!");
        }
        return Result.OK(list);

    }

    @ApiOperation(value="获取省级列表")
    @PostMapping(value = "/getProvince")
    public Result<?> getProvince(){
        //获取区所有省级地区   pid=0
        QueryWrapper<VeDictArea> wrapper = new QueryWrapper<>();
        wrapper.eq("pid",0);
        List<VeDictArea> list = veDictAreaService.list(wrapper);
        return Result.OK(list);
    }

    @ApiOperation(value="获取市/县级列表")
    @PostMapping(value = "/getCity")
    public Result<?> getCity(@ApiParam("上级路径ID") @RequestParam("id") Integer id){
        //获取区所有县级地区
        QueryWrapper<VeDictArea> wrapper = new QueryWrapper<>();
        wrapper.eq("pid",id);
        List<VeDictArea> list = veDictAreaService.list(wrapper);
        return Result.OK(list);
    }

    @ApiOperation(value="获取专业部")
    @PostMapping(value = "/getFaculty")
    public Result<?> getFaculty(){
//        BasicResponseBO<List<VeBaseFaculty>> facultyList = iVeBaseManageService.getFacultyAll();
//        List<VeBaseFaculty> list = facultyList.getResult();
        List<VeBaseFaculty> list = veBaseFacultyService.list();//2021.9.2
        return Result.OK(list);
    }

    @ApiOperation(value="获取专业")
    @PostMapping(value = "/getSpecialty")
    public Result<?> getSpecialty(@ApiParam("专业部ID") @RequestParam("facultyId") Long facultyId){
//        BasicResponseBO<List<VeBaseSpecialty>> specialtyList = iVeBaseManageService.getSpecialtyByFalId(facultyId);
//        List<VeBaseSpecialty> veBaseSpecialties = specialtyList.getResult();
        List<VeBaseSpecialty> veBaseSpecialties = veBaseSpecialtyService.list();//2021.9.2
        return Result.OK(veBaseSpecialties);
    }

    //李少君
    @ApiOperation(value="获取登录学生信息")
    @PostMapping(value = "/getStuMessage")
    public Result<?> getStuMessage(
            String xm, String ksh, String sfzh
    ){
        List<VeZsFenban> stuMessage = veZsFenbanService.getStuMessage(xm, ksh, sfzh);
        return Result.OK(stuMessage);
    }

    //提交学生缴费信息
    @AutoLog(value = "缴费-提交学生缴费信息")
    @ApiOperation(value="提交学生缴费信息", notes="缴费-提交学生缴费信息")
    @PostMapping("/addPayInfo")
    public Result<?> addPayInfo(@RequestBody VeZsPayInfo veZsPayInfo) {

        boolean a = veZsPayInfoService.addPayInfo(veZsPayInfo);
        if (a == true) {
            return Result.OK("提交缴费信息成功");
        } else {
            return Result.error("提交缴费信息失败");
        }
    }

    //提交学生缴费信息的图片
    @AutoLog(value = "缴费-提交学生缴费信息图片")
    @ApiOperation(value="提交学生缴费信息", notes="缴费-提交学生缴费信息图片")
    @PostMapping("/addPayInfoPic")
    public Result<?> addPayInfoPic(MultipartFile file) throws Exception {
        File document = null;
        //获取文件名
        String fileName = file.getOriginalFilename();
        //用点来切割获取文件类型注意//.需要加双斜杠正则表达式
        String[] arr = fileName.split("\\.");
        //获取文件后缀名
        String suffixName = arr[arr.length - 1];
        if (!suffixName.equalsIgnoreCase("jpg") && !suffixName.equalsIgnoreCase("png")) {
            return Result.error(400, "文件类型不能上传");
        }
        try {
            String originalFilename = file.getOriginalFilename();
            String[] filename = originalFilename.split("\\.");
            document = File.createTempFile(filename[0], filename[1]);
            file.transferTo(document);
            document.deleteOnExit();
        } catch (IOException e) {
            e.printStackTrace();
        }
        String docName = UUID.randomUUID().toString();
        //上传文件到指定的存储空间  第一个参数 bucketName  第二个参数 OSS存储路径  第三个参数 要上传的文件
        OSSClient ossClient = new OSSClient("oss-cn-beijing.aliyuncs.com","LTAI5tPnLGtPS6r8BpncZMrm","BAJbUlVLXD6or53Zcw1nC8uI87UpOs");
        PutObjectResult result = ossClient.putObject("exaplebucket-beijing",docName+"/"+ fileName, document);
        ossClient.shutdown();
        return Result.OK("https://exaplebucket-beijing.oss-cn-beijing.aliyuncs.com/"+docName+"/"+fileName);
    }

    //修改学生缴费信息
    @AutoLog(value = "缴费-修改学生缴费信息")
    @ApiOperation(value="修改学生缴费信息", notes="缴费-修改学生缴费信息")
    @PostMapping("/updatePayInfo")
    public Result<?> updatePayInfo(@RequestBody VeZsPayInfo veZsPayInfo) {

        boolean a = veZsPayInfoService.updatePayInfo(veZsPayInfo);
        if(a==true){
            return Result.OK("修改缴费信息成功");
        }else{
            return Result.error("修改缴费信息失败");
        }

    }

    //修改学生缴费信息图片
    @AutoLog(value = "缴费-修改学生缴费信息图片")
    @ApiOperation(value="修改学生缴费信息", notes="缴费-修改学生缴费信息图片")
    @PostMapping("/updatePayInfoPic")
    public Result<?> updatePayInfoPic(MultipartFile file) throws Exception {
        File document = null;
        //获取文件名
        String fileName = file.getOriginalFilename();
        //用点来切割获取文件类型注意//.需要加双斜杠正则表达式
        String[] arr = fileName.split("\\.");
        //获取文件后缀名
        String suffixName = arr[arr.length - 1];
        if (!suffixName.equalsIgnoreCase("jpg") && !suffixName.equalsIgnoreCase("png")) {
            return Result.error(400, "文件类型不能上传");
        }
        try {
            String originalFilename = file.getOriginalFilename();
            String[] filename = originalFilename.split("\\.");
            document = File.createTempFile(filename[0], filename[1]);
            file.transferTo(document);
            document.deleteOnExit();
        } catch (IOException e) {
            e.printStackTrace();
        }
        String docName = UUID.randomUUID().toString();
        //上传文件到指定的存储空间  第一个参数 bucketName  第二个参数 OSS存储路径  第三个参数 要上传的文件
        OSSClient ossClient = new OSSClient("oss-cn-beijing.aliyuncs.com","LTAI5tPnLGtPS6r8BpncZMrm","BAJbUlVLXD6or53Zcw1nC8uI87UpOs");
        PutObjectResult result = ossClient.putObject("exaplebucket-beijing",docName+"/"+ fileName, document);
        ossClient.shutdown();
        return Result.OK("https://exaplebucket-beijing.oss-cn-beijing.aliyuncs.com/"+docName+"/"+fileName);
    }

    //查看学生缴费信息
    @AutoLog(value = "缴费-查看学生缴费信息")
    @ApiOperation(value="查看学生缴费信息", notes="缴费-查看学生缴费信息")
    @PostMapping("/showPayInfo")
    public Result<?> showPayInfo(@RequestParam("id") Integer id){
        VeZsPayInfoVo veZsPayInfoVo = veZsPayInfoService.showPayInfo(id);
        return Result.OK(veZsPayInfoVo);
    }



    @AutoLog(value = "根据id查找贷款信息")
    @ApiOperation(value = "根据id查找贷款信息", notes = "根据id查找贷款信息")
    @PostMapping(value = "/selectById")
    public Result<?> selectById(@ApiParam("学生id") @RequestParam("id") Integer id) {
        return veZsStudentLoanService.selectById(id);
    }

    @AutoLog(value = "修改贷款")
    @ApiOperation(value = "修改贷款", notes = "修改贷款")
    @PostMapping("/updateLoan")
    public Result<?> updateLoan(@ApiParam("贷款id") @RequestParam("id") Integer id,
                                @ApiParam("开户行") @RequestParam("bank") String bank,
                                @ApiParam("高校账号名称") @RequestParam("bankName") String bankName,
                                @ApiParam("高校账号") @RequestParam("bankAccount") String bankAccount,
                                @ApiParam("贷款金额") @RequestParam("loanAmount") Long loanAmount,
                                @ApiParam("url") @RequestParam("bankReceipt") String bankReceipt,
                                @ApiParam("合同编号") @RequestParam("contractNo") String contractNo){
        boolean updateResult = veZsStudentLoanService.updateLoan(id, bank, bankName, bankAccount, loanAmount,bankReceipt,contractNo);
        if (updateResult) {
            return Result.OK("修改成功");
        }
        return Result.error("修改失败");
    }

    @AutoLog(value = "助学贷款申请")
    @ApiOperation(value = "助学贷款申请", notes = "助学贷款申请")
    @PostMapping(value = "/addLoan")
    public Result<?> addLoan(@ApiParam("学生id") @RequestParam("id") Integer id,
                             @ApiParam("开户行") @RequestParam("bank") String bank,
                             @ApiParam("高校账号名称") @RequestParam("bankName") String bankName,
                             @ApiParam("高校账号") @RequestParam("bankAccount") String bankAccount,
                             @ApiParam("贷款金额") @RequestParam("loanAmount") Long loanAmount,
                             @ApiParam("借款合同编号") @RequestParam("contractNo") String contractNo,
                             @ApiParam("url") @RequestParam("bankReceipt") String bankReceipt){
        Boolean addResult = veZsStudentLoanService.addLoan(id, bank, bankName, bankAccount, loanAmount, contractNo,bankReceipt );
        if (addResult) {
            return Result.OK("添加成功");
        }
        return Result.error("添加失败");
    }


    @AutoLog(value = "引导页-预分宿舍")
    @ApiOperation(value="引导页", notes="预分宿舍")
    @PostMapping("/getSusheBySpecIdAndBanjiId")
    public Result<?> getSusheBySpecIdAndBanjiId(@RequestParam("specId")Integer specId,@RequestParam("banjiId")Integer banjiId){
        QueryWrapper<VeZsFenban> wrapper = new QueryWrapper<>();
//        wrapper.select("susheId");
        if (specId != 0 && specId != null){
            wrapper.eq("specId",specId);
        }
        if (banjiId != 0 && banjiId != null){
            wrapper.eq("banjiId",banjiId);
        }
//        wrapper.eq("SFKY",1);//查询可用宿舍
//        wrapper.eq("status",1);//查询正常宿舍
        List<VeZsFenban> susheIds = veFenSusheService.list(wrapper);
        HashSet<Integer> l = new HashSet<>();
        for (VeZsFenban v : susheIds){
            l.add(v.getSusheId());
        }

//        List<VeDormSusheEntity> suShes = new ArrayList<>();
        List<Map<String,Object>> suShes = new ArrayList<>();
        for (Integer v : l){
            if (v!= null){
                VeDormSusheEntity veDormSusheEntity = veDormSusheService.getById(v);
                if(veDormSusheEntity!=null){
                    //根据房间编码获取房间与学生关系表数据
                    QueryWrapper<VeDormStudent> queryWrapper = new QueryWrapper<>();
                    VeDormSusheEntity sushe = veDormSusheService.getById(v);
                    queryWrapper.eq("FJBM",sushe.getFjbm());
                    queryWrapper.eq("SSLBM",sushe.getJzwh());
                    List<VeDormStudent> list = veDormStudentService.list(queryWrapper);
                    //整合返回数据
                    Map<String ,Object> res = new HashMap<>();
                    res.put("sushe",veDormSusheEntity);
                    res.put("guanxi",list);
                    suShes.add(res);
                }
            }
        }

        return Result.OK(suShes);
    }
    //林彬辉
    @AutoLog(value = "引导页-学生选择床位")
    @ApiOperation(value="引导页", notes="学生选择床位")
    @PostMapping("/chooseSushe")
    @Transactional
    public Result<?> chooseSushe(@ApiParam("用户id") @RequestParam("userId")Long userId,@ApiParam("学号") @RequestParam("xh")String xh
            ,@ApiParam("姓名") @RequestParam("xm")String xm,@ApiParam("校区号") @RequestParam("xqh")Long xqh
            ,@ApiParam("房间编码") @RequestParam("fjbm")Long fjbm,@ApiParam("床位号") @RequestParam("cwh")String cwh
            ,@ApiParam("楼层号") @RequestParam("lch")Long lch,@ApiParam("宿舍楼编号") @RequestParam("sslbm")Long sslbm){
        // 获取redis存的用户值
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        VeDormStudent veDormStudent = new VeDormStudent();
        if (user != null){
            veDormStudent.setCreateUserId(Long.parseLong(user.getId()));
            veDormStudent.setCreateUserName(user.getRealname());
        }else {
            veDormStudent.setCreateUserId(0L);
            veDormStudent.setCreateUserName("暂无用户");
        }

        veDormStudent.setCwh(cwh);
        veDormStudent.setFjbm(fjbm);
        veDormStudent.setLch(lch);
        veDormStudent.setTerminalId(1L);
        veDormStudent.setSslbm(sslbm);
        veDormStudent.setXh(xh);
        veDormStudent.setXm(xm);
        veDormStudent.setXqh(xqh);
        veDormStudent.setUserId(userId);

        String cTime = new Date().getTime()+"";
        Long creatTime = Long.parseLong(cTime.substring(0,cTime.length()-3));
        veDormStudent.setCreateTime(creatTime);
        veDormStudent.setRzsj(creatTime);
        //判断是否已选择床位
        QueryWrapper<VeDormStudent> checkRe = new QueryWrapper<>();
        checkRe.eq("XH",xh);
        checkRe.eq("userId",userId);
        VeDormStudent student = veDormStudentService.getOne(checkRe);
        if (student != null){
            return Result.error("已有床位，请勿重复选择");
        }
            //获取宿舍信息
            QueryWrapper<VeDormSusheEntity> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("FJBM",fjbm);
            queryWrapper.eq("JZWH",sslbm);
            VeDormSusheEntity veDormSusheEntity = veDormSusheService.getOne(queryWrapper);
            //加入后宿舍信息变化
            VeDormSusheEntity updateSushe = new VeDormSusheEntity();
            if (veDormSusheEntity.getKzrs()>veDormSusheEntity.getYzrs()){//判断是否满人
                updateSushe.setYzrs(veDormSusheEntity.getYzrs()+1);
//                updateSushe.setKzrs(veDormSusheEntity.getKzrs()-1);
                boolean res = veDormStudentService.save(veDormStudent);
                if (res){
                    if (veDormSusheEntity.getKzrs()==veDormSusheEntity.getYzrs()+1){//满人则修改宿舍为不可用
                        updateSushe.setSfky(0L);
                    }
                    UpdateWrapper<VeDormSusheEntity> wrapper = new UpdateWrapper<>();
                    wrapper.eq("JZWH",sslbm);
                    wrapper.eq("FJBM",fjbm);
                    veDormSusheService.update(updateSushe,wrapper);
                }else {
                    return Result.error("宿舍-学生信息保存报错");
                }
            }else {
                return Result.error("房间已满");
            }

        return Result.OK("床位选择成功");
    }

    @AutoLog(value = "上传图片")
    @ApiOperation(value = "上传图片", notes = "上传图片")
    @PostMapping(value = "/upload")
    public Result<?> upload(@ApiParam("文件") @RequestParam("file") MultipartFile file) throws Exception {
        File document = null;
        //获取文件名
        String fileName = file.getOriginalFilename();
        //用点来切割获取文件类型注意//.需要加双斜杠正则表达式
        String[] arr = fileName.split("\\.");
        //获取文件后缀名
        String suffixName = arr[arr.length - 1];
        if (!suffixName.equalsIgnoreCase("jpg") && !suffixName.equalsIgnoreCase("png")) {
            return Result.error(400, "文件类型不能上传");
        }
        try {
            String originalFilename = file.getOriginalFilename();
            String[] filename = originalFilename.split("\\.");
            document = File.createTempFile(filename[0], filename[1]);
            file.transferTo(document);
            document.deleteOnExit();
        } catch (IOException e) {
            e.printStackTrace();
        }
        String docName = UUID.randomUUID().toString();
        //上传文件到指定的存储空间  第一个参数 bucketName  第二个参数 OSS存储路径  第三个参数 要上传的文件
        OSSClient ossClient = new OSSClient("oss-cn-beijing.aliyuncs.com","LTAI5tPnLGtPS6r8BpncZMrm","BAJbUlVLXD6or53Zcw1nC8uI87UpOs");
        PutObjectResult result = ossClient.putObject("exaplebucket-beijing",docName+"/"+ fileName, document);
        ossClient.shutdown();
        return Result.OK("https://exaplebucket-beijing.oss-cn-beijing.aliyuncs.com/"+docName+"/"+fileName);

    }
    //上传附件
    @AutoLog(value = "招生计划管理-上传附件")
    @PostMapping("/uploadFujian")
    public Result<?> uploadFujian(@ApiParam("文件") @RequestParam("file") MultipartFile file) throws Exception {
        File document = null;
        //获取文件名
        String fileName = file.getOriginalFilename();
        //用点来切割获取文件类型注意//.需要加双斜杠正则表达式
        String[] arr = fileName.split("\\.");
        //获取文件后缀名
        String suffixName = arr[arr.length - 1];
        if (!suffixName.equalsIgnoreCase("jpg") && !suffixName.equalsIgnoreCase("png")) {
            return Result.error(400, "文件类型不能上传");
        }
        try {
            String originalFilename = file.getOriginalFilename();
            String[] filename = originalFilename.split("\\.");
            document = File.createTempFile(filename[0], filename[1]);
            file.transferTo(document);
            document.deleteOnExit();
        } catch (IOException e) {
            e.printStackTrace();
        }
        String docName = UUID.randomUUID().toString();
        //上传文件到指定的存储空间  第一个参数 bucketName  第二个参数 OSS存储路径  第三个参数 要上传的文件
        OSSClient ossClient = new OSSClient("oss-cn-beijing.aliyuncs.com","LTAI5tPnLGtPS6r8BpncZMrm","BAJbUlVLXD6or53Zcw1nC8uI87UpOs");
        PutObjectResult result = ossClient.putObject("exaplebucket-beijing",docName+"/"+ fileName, document);
        ossClient.shutdown();
        String fileUrl = "https://exaplebucket-beijing.oss-cn-beijing.aliyuncs.com/"+docName+"/"+fileName;
        VeFileFiles fileFiles = new VeFileFiles();

//        String[] arr = fileName.split("\\.");
//        String suffixName = arr[arr.length - 1];
        fileFiles.setExt(suffixName);
        fileFiles.setName(fileName);
        fileFiles.setSourcefile(fileUrl);
        fileFiles.setSize(file.getSize());
        fileFiles.setCreatetime(System.currentTimeMillis() / 1000);
        if (veZsPlanService.findFileId(fileUrl)==null){
            veZsPlanService.addFujian(fileFiles);
        }
        Integer fileId = veZsPlanService.findFileId(fileUrl);
//        return Result.OK("https://exaplebucket-beijing.oss-cn-beijing.aliyuncs.com/"+docName+"/"+fileName);
        return Result.OK(fileId);
    }
    //lbh
    @ApiOperation(value="保存数据增加")
    @PostMapping(value = "/save")
    public Result<?> saveMsg(@RequestBody VeZsReportMsg veZsReportMsg){
        System.out.println(veZsReportMsg.getEndPlaceId()+"endplace");
        //数据校验
        //身份证号唯一
        QueryWrapper<VeZsReportMsg> wrapper = new QueryWrapper<>();
        wrapper.eq("stu_ID",veZsReportMsg.getStuID());
        VeZsReportMsg vreportMsg= veZsReportMessageService.getOne(wrapper);
        if(vreportMsg!=null){
            return Result.error("添加失败，身份证号已存在");
        }
        //添加交通工具名称，到达地点名称
        //交通工具信息获取
        if (veZsReportMsg.getVehicleId() != null&& !veZsReportMsg.getVehicleId().equals("0")){
            QueryWrapper<SysDictItem> vehicleWrapper = new QueryWrapper<>();
            vehicleWrapper.eq("id",veZsReportMsg.getVehicleId());
            SysDictItem vehicle = sysDictItemService.getOne(vehicleWrapper);
            veZsReportMsg.setVehicleName(vehicle.getItemText());
        }

        QueryWrapper<SysDictItem> endPlaceWrapper = new QueryWrapper<>();
        endPlaceWrapper.eq("id",veZsReportMsg.getEndPlaceId());

        SysDictItem endplace = sysDictItemService.getOne(endPlaceWrapper);
        veZsReportMsg.setEndPlace(endplace.getItemText());

        //添加出发地点名称
        if (veZsReportMsg.getStartPlaceId()!=null){
            VeDictArea area = veDictAreaService.getById(veZsReportMsg.getStartPlaceId());
            veZsReportMsg.setStartPlace(area.getName());
            //添加省份id
            veZsReportMsg.setProvinceId((area.getPid()));
        }


        boolean res = veZsReportMessageService.save(veZsReportMsg);
        if (res==true){
            return Result.OK("添加成功");
        }else {
            return Result.error("添加失败");
        }

    }

}
